#!/usr/bin/env python
# Different wallpaper source modules

from html_re_lib import *
from netlibs import *
from debugger import *
import configs
from time import *
import sys
import os
import random
import urllib2
import urlparse

class WallPaperModules:
    def __init__(self):
        self.wallpaper_modules = [
            ["National Geographic", get_ng_wallpaper, "http://photography.nationalgeographic.com/photography/photo-of-the-day"],
            ["NASA Image of Day", get_nasa_wallpaper, "http://www.nasa.gov/multimedia/imagegallery/iotd.html"],
            ["InterfaceLIFT", get_interfaceLift_wallpaper, "http://interfacelift.com/wallpaper/"],
            ["Tor.com", get_tor_wallpaper, "http://www.tor.com/wallpaper.html"],
        ]

    def list_modules(self):
        for i in range(len(self.wallpaper_modules)):
            print "%2d: %s" % (i + 1, self.wallpaper_modules[i][0])

    def run_module(self, index):
        if index < 1 or index > self.num_of_modules():
            return None
        print self.wallpaper_modules[index - 1][0]
        return self.wallpaper_modules[index - 1][1]()
    
    def num_of_modules(self):
        return len(self.wallpaper_modules)
        

# Returns a dict of (year, month, day of month)
def getdate():
    return {"year" : strftime("%Y"), "month" : strftime("%m"), "day" : strftime("%d")}

def download_image(link, prefix, name=None):
    imagedata = myurlopen(link).read()
    DEBUG.p("Image data:\n")
    DEBUG.p(repr(imagedata[0:256]))

    if name:
        outputfile = os.path.join(configs.Configs["OUTPUT_PATH"], prefix + "_" + name + ".jpg")
    else:
        outputfile = os.path.join(configs.Configs["OUTPUT_PATH"], prefix + "_" + getdate()["year"] + getdate()["month"] + getdate()["day"] + ".jpg")
    imagefile = open(outputfile, 'wb')
    imagefile.write(imagedata)
    imagefile.close()

    return outputfile

#
# Get wallpaper of the day from National Graphics web page
#
def get_ng_wallpaper():

    # Configs
    NG_WP_URL = "http://photography.nationalgeographic.com/photography/photo-of-the-day"
    SEARCH_LINK = 'class="wallpaper"'
    SEARCH_STR = "1024 x 768"
    IMAGE_BASE_URL = "http://photography.nationalgeographic.com"
    PREFIX = "ng"

    # First we try to find the detailed wallpaper page
    doc = myurlopen(NG_WP_URL).read()

    wallpaper_page_link = find_link_with_str(doc, SEARCH_LINK)
    if wallpaper_page_link == None:
        print "Can't find detailed wallpaper page link."
        return

    wallpaper_page_link = IMAGE_BASE_URL + wallpaper_page_link
    DEBUG.p(wallpaper_page_link)

    # Then we get the image link. The link is like:
    # <img alt="...." src="/staticfiles/NGS/Shared/StaticFiles/Photography/Images/POD/b/big-cypress-orange-sunset-90701-ga.jpg">
    doc = myurlopen(wallpaper_page_link).read()

    wallpaper_image_link = find_link_with_str(doc, SEARCH_STR)
    if wallpaper_image_link == None:
        print "Can't find the wallpaper image link."
        return

    # Complete the image link
    wallpaper_image_link = IMAGE_BASE_URL + wallpaper_image_link
    DEBUG.p(wallpaper_image_link)

    # Then we download the image
    return download_image(wallpaper_image_link, PREFIX)

#
# Get wallpaper of the day from NASA web page
#
def get_nasa_wallpaper():
    # Configs
    URL = "http://www.nasa.gov/rss/lg_image_of_the_day.rss"
    SEARCH_STR = "/images/content/"
    PREFIX = "nasa"

    # Parse RSS page and get image link
    doc = myurlopen(URL).read()

    wallpaper_image_link = find_content_in_tag_by_str(doc, "url", SEARCH_STR)
    if wallpaper_image_link == None:
        print "Can't find detailed wallpaper page link."
        return

    # Change image size of 1024x768
    #m = re.compile(r"(.+_)\d+-\d+(\.\w{3})").search(wallpaper_image_link)
    #if not m:
    #    print "Image link invalid"
    #    return
    #wallpaper_image_link = m.group(1) + "1024-768" + m.group(2)

    DEBUG.p(wallpaper_image_link)

    # Then we download the image
    return download_image(wallpaper_image_link, PREFIX)

#
# Get wallpaper from high ratings InterfaceLIFT page
#
def get_interfaceLift_wallpaper():
    # Configs
    URL = "http://interfacelift.com/wallpaper/index.php?sort=ratings&page="
    IMG_BASE = "http://interfacelift.com/dl/wallpaper/"
    PAGES_RANGE = [1, 40]
    SEARCH_STR = "/wallpaper/previews/"
    PREFIX = "InLIFT"
    RESOLUTIONS = ["1600x1200", "1400x1050", "1280x960", "1024x768"]

    # Get random page content
    url = URL + str(random.randint(PAGES_RANGE[0], PAGES_RANGE[1]))
    DEBUG.p(url)
    doc = myurlopen(url).read()

    # Parse to get image id and name
    images = {}
    links = find_property_in_tag_by_str("src", doc, "img", SEARCH_STR, CLOSETAG, True)
    for link in links:
        m = re.search(r'.+/(\d+)_(.+)\.jpg', link, re.IGNORECASE)
        if m:
            images[m.group(1)] = m.group(2)

    if images:
        (img_id, img_name) = random.choice(images.items())
        for resolution in RESOLUTIONS:
            wallpaper_image_link = IMG_BASE + img_id + "_" + img_name + "_" + resolution + ".jpg"
            DEBUG.p(wallpaper_image_link)
            try:
                imagedata = myurlopen(wallpaper_image_link).read()
            except urllib2.HTTPError, e:
                DEBUG.p("HTTPError:")
                DEBUG.p(e)
                continue
            else:
                if imagedata.find("404") >= 0:
                    DEBUG.p("404 page found")
                else:
                    return download_image(wallpaper_image_link, PREFIX, img_id + "_" + img_name)
    else:
        print "Can't find wallpaper image links."


#
# Get wallpaper of the day from NASA web page
#
def get_tor_wallpaper():
    # Configs
    URL = "http://www.tor.com/wallpaper.html"
    SEARCH_STRs = ["1600x1200", "1680x1050", "1280x1024", "1280x800", "1024x768"]
    PREFIX = "tor"

    # Parse RSS page and get image link
    doc = myurlopen(URL).read()

    links = []
    for search_sr in SEARCH_STRs:
        # For each size in SEARCH_STRs, search for all occurance in page
        links += find_link_with_str(doc, search_sr, all=True)

        if len(links) >= 2:
            links = links[:2]
            break
    DEBUG.p(links)

    # Can't find the link
    if not len(links):
        print "Can't find wallpaper link."
        return

    wallpaper_image_link = random.choice(links)
    filename = os.path.basename(wallpaper_image_link)
    wallpaper_image_link = urlparse.urljoin(URL, wallpaper_image_link)
    DEBUG.p(wallpaper_image_link)

    # Then we download the image
    return download_image(wallpaper_image_link, PREFIX, filename[:-4])
